package com.hksj.Intelligentmanagement.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.Intelligentmanagement.dto.MusicQuery;
import com.hksj.Intelligentmanagement.entity.Music;
import com.hksj.Intelligentmanagement.mapper.MusicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 歌曲信息表 服务类
 * @author chenxingqing
 */
@Service
public class MusicService extends ServiceImpl<MusicMapper, Music> {
    @Autowired
    private FolderService folderService;

    @Value("${hk.file.music:'/'}")
    private String baseFilePath;

    public void uploadMusic(Long folderId, MultipartFile[] multipartFile) {
        String dirPath = folderService.getDirPath(folderId);
        Integer count = lambdaQuery().eq(Music::getFolderId, folderId).count();
        List<Music> musicList = new ArrayList<>();
        Music tempMusic = null;
        for (MultipartFile file : multipartFile) {
            String name = file.getOriginalFilename();
            long size = file.getSize();
            //获取到文件后缀名
            int separator = name.lastIndexOf(".");
            String type = name.substring(separator + 1);
            String fileName = name.substring(0,separator);
            try {
                //将临时文件转存到指定的地址 dirPath+"/"+该完整文件名
                file.transferTo(FileUtil.file(dirPath + "/" + name));
            } catch (IOException e) {
                //转存出现问题,抛出异常
                throw new RuntimeException("上传文件失败");
            }
            tempMusic = new Music();
            tempMusic.setName(fileName);
            tempMusic.setPath(dirPath);
            tempMusic.setSize(size);
            tempMusic.setType(type);
            tempMusic.setSeq(++count);
            tempMusic.setFolderId(folderId);
            musicList.add(tempMusic);
        }
        this.saveBatch(musicList);
    }

    public void deleteMusic(Long id) {
        Music music = getById(id);
        FileUtil.del(FileUtil.file(music.getPath() + "/" + music.getName() + "." + music.getType()));

        removeById(id);
    }

    public IPage<Music> pageMusic(MusicQuery query) {
        IPage<Music> page = new Page<>(query.getPageNum(), query.getPageSize());
        List<Music> list = baseMapper.pageMusic(query, query.getDisAblePage() ? null : page);
        page.setRecords(list);
        return page;
    }

    public void syncMusic(HttpServletResponse response) {
        try {
            File zip = ZipUtil.zip(baseFilePath);
            // 设置响应头，告诉浏览器返回的数据是一个压缩包
            String fileName = "music.zip";
            try {
                // 设置响应内容类型为二进制流
                response.setContentType("application/octet-stream");
                // 设置响应头，告诉浏览器返回的数据是一个文件，并指定文件名称
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                // 输入流，通过输入流读取文件内容
                FileInputStream fileInputStream = new FileInputStream(zip);
                // 获取响应输出流
                ServletOutputStream outputStream = response.getOutputStream();

                // 将文件内容写入到响应输出流中
                int len;
                byte[] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                // 关闭输入流和输出流
                fileInputStream.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
